package org.tinygame.herostory.cmdhandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.login.LoginService;
import org.tinygame.herostory.login.db.UserEntity;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;


/**
 * @author anan
 * @create 2022-05-06 0:17
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {

    static private final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if(null == ctx || null == cmd) return;

        String userName = cmd.getUserName();
        String password = cmd.getPassword();
        if(null == userName || null == password) return;

        LoginService.getInstance().userLogin(userName, password, (userEntity) -> {
            GameMsgProtocol.UserLoginResult.Builder builder = GameMsgProtocol.UserLoginResult.newBuilder();

            LOGGER.info("当前线程 = {}", Thread.currentThread().getName());

            if(null == userEntity){
                builder.setUserId(-1);
                builder.setUserName("");
                builder.setHeroAvatar("");

            }else{
                User newUser = new User();
                newUser.userId = userEntity.userId;
                newUser.userName = userEntity.userName;
                newUser.heroAvatar = userEntity.heroAvatar;
                newUser.currHp = 100;
                UserManager.addUser(newUser);

                //将用户Id保存到session
                ctx.channel().attr(AttributeKey.valueOf("userId")).set(newUser.userId);
                builder.setUserId(userEntity.userId);
                builder.setUserName(userEntity.userName);
                builder.setHeroAvatar(userEntity.heroAvatar);

            }
            GameMsgProtocol.UserLoginResult newResult = builder.build();
            ctx.writeAndFlush(newResult);
            return null;
        });


    }
}
